package com.example.myapplication;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @author: rongfeng
 * @date: 2020/9/2
 * @description
 */
public class iciba {
    static volatile int index = 1;

    static ExecutorService pool;

    static Map<Integer, String> map = new Hashtable<>();

    static int maxPage = 200;
    static int classId = 705;

    static int bookId = 1;

    public static void main(String[] args) {
        pool = Executors.newFixedThreadPool(5);
        start();
    }

    public static void start() {
        for (int i = 0; i < 5; i++) {
            nextClass();
        }
    }

    public static void nextClass() {
        pool.execute(new Runnable() {
            @Override
            public synchronized void run() {
                if (index <= maxPage) {
                    String url = "http://word.iciba.com/?action=words&class=" + classId + "&course=" + index;
                    index++;
                    int p = index;
                    System.out.println("ssss " + index);
                    new Query2().getDns(url, p);
                }
            }
        });
        if (map.size() == maxPage) {
            saveFile();
            if (classId <= 44) {
                index=1;
                classId++;
                bookId++;
                map.clear();
                start();
            }else {

            }
        }
    }


    public static void saveFile() {
        File file = new File("D:\\wrf\\test\\" + bookId + ".txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
//            String json = GsonUtil.toJson(stringList);
            StringBuffer stringList = new StringBuffer();
            for (int i = 1; i < maxPage + 1; i++) {
                String str = map.get(i);
                if (str != null) {
                    stringList.append(map.get(i));
                }
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(stringList.toString());
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("保存完成 " + classId);
    }


    public static class Query2 {
        StringBuffer stringList = new StringBuffer();

        public void getDns(String url, int indexs) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build();
            final Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }

                @Override
                public void onResponse(Call call, @NotNull okhttp3.Response response) throws IOException {
                    if (response.body() != null) {
                        String html = response.body().string();
//                    System.out.println(html);
                        nextSub(html);

                        map.put(indexs - 1, stringList.toString());
                        nextClass();
                    }
                }
            });
        }

        public void nextSub(String html) {
            String tag1 = "<div class=\"word_main_list_w\">";
            String tag2 = "<span title=";
            int index = html.indexOf(tag1);
            if (index > 0) {
                String subHtml1 = html.substring(index + tag1.length());
                int index2 = subHtml1.indexOf(tag2);
                if (index2 > 0) {
                    String subHtml2 = subHtml1.substring(index2 + tag2.length());
                    int index3 = subHtml2.indexOf(">");
                    String subHtml3 = subHtml2.substring(1, index3 - 1);
                    stringList.append(subHtml3 + "\n");
                    nextSub(subHtml2);
                }

            }
        }
    }

}
